<template>
    <div class="main">
        <div class="main-header" style="display: flex;justify-content: space-between;">
            <div style="display: flex;flex:1;flex-wrap: wrap;align-items: center;">
                <el-input v-model="searchParamCp.keyword" placeholder="请输入任务名称或地址" style="width:200px"></el-input>
               <!-- <el-select clearable style="width:120px" class="ml-10" v-model="searchParamCp.has_content" placeholder="有/无诉求">
                    <el-option label="全部"   value=""></el-option>
                    <el-option label="有诉求" :value="1"></el-option>
                    <el-option label="无诉求" :value="2"></el-option>
                </el-select> -->
				<el-select v-model="searchParamCp.task_type" placeholder="请选择任务类型" style="width:200px;margin-left: 10px;">
				    <el-option v-for="(item,index) in typeList" :key="index" :label="item.title" :value="item.id">
				    </el-option>
				</el-select>
				<!-- <el-select v-model="searchParam.status" placeholder="请选择认证状态" style="width:200px;margin-left: 10px;">
				    <el-option v-for="(item,index) in statusList" :key="index" :label="item" :value="index">
				    </el-option>
				</el-select> -->
                <!-- <el-date-picker style="width:340px" clearable class="ml-10" v-model="searchParamCp.search_time"
                    value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker> -->
				<div style="margin: 0 0 0 20px;">派发时间：</div>
				<el-date-picker
				 clearable class="ml-10"
				      v-model="searchParamCp.search_time"
				      type="datetimerange"
					  value-format="yyyy-MM-dd"
				      :picker-options="pickerOptions"
				      range-separator="至"
				      start-placeholder="开始日期"
				      end-placeholder="结束日期"
				      align="right">
				    </el-date-picker>
                <div class="ml-10">
                    <el-button type="primary" @click="searchinfo">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </div>
            </div>
            <div style="display: flex;">
                <el-button  v-if="$auth('add')" type="primary" @click="openmodel()">添加</el-button>
				<!-- <el-button type="danger" @click="exportExcel()">导出</el-button> -->
                <el-button v-if="$auth('delete')" type="danger" @click="selectdel" :disabled="!selection.length">批量删除</el-button>
            </div>
        </div>
        <el-table ref="table" class="main-table" header-align="center" border :data="list" @selection-change="onSelectionChange" height="100%"
            row-key="id" header-cell-class-name="main-table-header" @row-click="onRowClick">
            <el-table-column type="selection" width="50"> </el-table-column>
            <el-table-column  show-overflow-tooltip label="自提点名称" prop="task_name"></el-table-column>
			
            <!-- <el-table-column v-if="$route.query.type" show-overflow-tooltip label="联系方式" prop="mass_mobile" width="120px"></el-table-column> -->
            
			 <el-table-column show-overflow-tooltip label="联系人" prop="task_address" ></el-table-column>
			 <el-table-column show-overflow-tooltip label="联系电话" prop="content" ></el-table-column>

            <!-- <el-table-column label="创建时间" prop="createtime">
                <template slot-scope="{row}">
                    {{ row.createtime | formatDate }}
                </template>
            </el-table-column> -->
			<el-table-column show-overflow-tooltip label="地址" prop="send_count" ></el-table-column>
			<el-table-column show-overflow-tooltip label="经纬度" prop="complete_count" ></el-table-column>
			<el-table-column show-overflow-tooltip label="任务类型" prop="cadre_mobile">
				<template slot-scope="{row}">
				    <div class="line-one" :title="row.task_type">
						<el-tag v-if="row.task_type==1">日任务(巡防员)</el-tag>
						<el-tag v-else type="success">周任务(民警)</el-tag>
				        <!-- {{ row.task_type==1?'日任务(巡防员)':'周任务(民警)' }} -->
						<!-- 任务类型1日任务(巡防员) 2周任务(民警) -->
				    </div>
				</template>
			</el-table-column>
            <el-table-column label="操作" >
                <template slot-scope="{row}">
                    <el-button type="warning" @click.stop="openmodel(row)">编辑</el-button>
					<el-button type="primary" @click.stop="openDialogVisible(row)">派发</el-button>
					<el-button type="danger" @click.stop="toinfo(row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="main-pagination" :current-page.sync="searchParam.page" :page-size="searchParam.limit"
            :total="searchParam.total" @current-change="onCurrentChange"
            layout="total,jumper,prev,pager,next"></el-pagination>
			<el-dialog
			  title="派发任务"
			  :visible.sync="DialogVisible"
			  width="50%"
			  @close="onDialogClose"
			  append-to-body
			  :key="formDataStatus"
			  center>
			  <distribute ref="homeDel" :formData="distributeinfo" :userlist="userlist" :classlist="classlist" @search="distribute"></distribute>
			</el-dialog>
		<el-dialog
		  :title="title"
		  :visible.sync="centerDialogVisible"
		  width="60%"
		  center>
		  <add v-if="centerDialogVisible" :formData="userinfo" @search="search"></add>
		</el-dialog>
    </div>
</template>
<script>
// import companyCate from '@/components/company-cate.vue'
// import supervisorSelect from '@/components/supervisor-select.vue'
import { imghttp,get,post,del } from '@/assets/js/http'
import add from './components/info.vue'
import distribute from './components/distribution.vue'
export default {
    components: { add,distribute },
    data() {
        return {
            list: [],
            selection: [],
            addShow: false,//添加显示
			centerDialogVisible:false,//详情弹窗
			DialogVisible:false,//派发任务弹窗
			title:'',//弹窗标题
			userinfo:{},//列表行信息
			distributeinfo:{},//派发信息
			userlist:[],//周任务
			classlist:[],//分组列表
			typeList:[{id:1,title:'日任务(巡防员)'},{id:2,title:'周任务(民警)'}],//任务类型 1日任务(巡防员) 2周任务(民警)
			statusList:['未认证','认证待审核','认证通过','认证驳回'],//认证状态 0未认证 1认证待审核 2认证通过 3认证驳回
			ids:[],
			reason:'',
            searchParam: {
                page: 1,
                limit: 20,
                total: 0,
                cadre_id:'',
                search_time: [],
                status:'',
				task_type:'',
				keyword:'',
            },
            searchParamCp:{
            },
			formDataStatus:false,
			pickerOptions: {
			          shortcuts: [{
			            text: '最近一周',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			              picker.$emit('pick', [start, end]);
			            }
			          }, {
			            text: '最近一个月',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			              picker.$emit('pick', [start, end]);
			            }
			          }, {
			            text: '最近三个月',
			            onClick(picker) {
			              const end = new Date();
			              const start = new Date();
			              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			              picker.$emit('pick', [start, end]);
			            }
			          }]
			        },
        }
    },
    created() {
        Object.assign(this.searchParam,this.$route.query?this.$route.query:{})
        Object.assign(this.searchParamCp,this.$route.query?this.$route.query:{})
        this.getList()
		this.getcommunity()
		this.getclasslist()
    },
    watch:{
        '$route':{
            deep:true,
            handler(){
                this.reset()
            }
        }
    },
    methods: {
        async getList() {
            this.$loading()
            // let { list,total } = 
			await get({
			    url: '/admin/server.Task/index',
			    params: {
			        ...this.searchParam,
			        ...{
			            // server_type:this.$route.query.type?2:1,
			            search_time:this.searchParam.search_time.length?this.searchParam.search_time.join(' - '):''
			        }
			    }
			}).then(res=>{
				this.list = res.list
				this.searchParam.total = res.total
				this.$loading().close()
			})
            
        },
		//添加,编辑弹窗
		openmodel(row){
			this.userinfo.img=[]
			if(row){//编辑
				this.title="编辑任务"
				get({
					url:'/admin/server.Task/edit',
					params:{
						id:row.id
					}
				}).then(res=>{
					
					res.row.location={lng:res.row.lng,lat:res.row.lat}
					// const time = this.userinfo
					res.row.daterange = [res.row.start_time*1000,res.row.end_time*1000]
					if(res.row.img){
						res.row.img = [{
							name:res.row.img,
							url:res.row.img
						}]
						console.log(res.row.img)
					}
					this.userinfo = res.row
				})
				// this.userinfo = row
				// this.userinfo.location={lng:row.lng,lat:row.lat}
			}else{//添加
				this.userinfo = {}
				this.userinfo.location={lng:28.692306,lat:115.868225}
				this.title="添加任务"
			}
			this.centerDialogVisible = true
			this.formDataStatus = true;
		},
		close(){
			this.centerDialogVisible = false
		},
		//打卡列表
		toinfo(row){
			this.$router.push({path:'/sign',query:{task_id:row.id}})
		},
		//任务编辑，添加
		search(result){
			const info = JSON.parse(JSON.stringify(result))
			console.log(info)
			info.lat = info.location.lat
			info.lng = info.location.lng
			if(info.img){
				info.img = info.img[0].url
			}
			if(info.id){
				post({
					url:'/admin/server.Task/edit',
					data:info
				}).then(res=>{
					this.close()
					this.getList()
				})
			}else{
				post({
					url:'/admin/server.Task/add',
					data:info
				}).then(res=>{
					this.close()
					this.getList()
				})
			}
		},
		//派发任务弹窗admin/basic.Masses/index
		openDialogVisible(row){
			this.distributeinfo = row
			this.DialogVisible = true
		},
		//派发任务
		distribute(result){
			const info = JSON.parse(JSON.stringify(result))
			console.log(info)
			// if(info.group_id){
			// 	info.group_id = (info.group_id).join(',')
			// }
			post({
				url:'/admin/server.Task/sendTask',
				data:{
					user_ids:info.user_ids,
					id:info.id,
					remark:info.remark,
					group_id:info.group_id
				}
			}).then(res=>{
				this.getList()
				this.DialogVisible = false
			})
		},
		//社区列表
		getcommunity(){
			get({
				url:'/admin/user.RealmeritUser/index',
				params:{
					type:1,//角色1社区民警 2综治巡逻队员 3网格员
					status:2,//认证状态 0未认证 1认证待审核 2认证通过 3认证驳回
				},
				loading: true
			}).then(res=>{
				this.userlist = res.list
			})
		},
		//获取分组列表
		getclasslist(){
			get({
				url:'/admin/user.Group/index',
			}).then(res=>{
				this.classlist = res.list
			})
		},
		onDialogClose(){
			this.$refs['homeDel'].onCancel()
			this.$refs.table.clearSelection();
		},
        reset() {
            this.searchParamCp = this.$options.data().searchParam
            this.searchParam = this.$options.data().searchParam
            this.getList()
        },
        searchinfo() {
            this.searchParam.page = 1
            this.searchParam = { ...this.searchParam, ...this.searchParamCp }
            this.getList()
        },
        onCurrentChange() {
            this.getList()
        },
        onRowClick(row) {
            this.$refs.table.toggleRowSelection(row);
        },
        onSelectionChange(selection) {
            this.selection = selection;
        },
		//批量审核
		selectexamine(){
			this.$confirm(
			    `此操作将通过该${this.selection.length}个用户, 是否继续?`,
			    "提示",
			    {
			        confirmButtonText: "确定",
			        cancelButtonText: "取消",
			        type: "warning"
			    }
			)
			    .then(async () => {
			        this.ids = []
					for (let i = 0; i < this.selection.length; i++) {
					    this.ids.push(this.selection[i].id)
					}
			        await this.$post({
			            url: "/admin/user.RealmeritUser/checkAll",
			            data:{
							ids:this.ids
						},
			            loading: true
			        });
			        this.getList()
			    })
			    .catch(() => {
			        this.$refs.table.clearSelection();
			    });
		},
		//批量拒绝
		selectdelete(){
			this.$prompt('请输入拒绝原因',`此操作将通过该${this.selection.length}个用户, 是否继续`, {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
			          // inputErrorMessage: '邮箱格式不正确'
			        }).then(async({ value }) => {
			          this.$message({
			            type: 'success',
			            message:  value
			          });
					  this.reason = value
					  console.log(value,this.reason)
					  for (let i = 0; i < this.selection.length; i++) {
					      this.ids.push(this.selection[i].id)
					  }
					  await this.$post({
					      url: "/admin/user.RealmeritUser/rejectAll",
					      data:{
					  		id:this.ids,
							reason:this.reason
					  	},
					      loading: true
					  });
					  this.getList()
			        }).catch(() => {
			           this.$refs.table.clearSelection();     
			        });
			
		},
        selectdel() {
            this.$confirm(
                `此操作将永久删除该${this.selection.length}个企业, 是否继续?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            )
                .then(async () => {
                    let query = "?";
                    for (let i = 0; i < this.selection.length; i++) {
                        const item = this.selection[i];
                        if (i > 0) {
                            query += "&ids[]=" + item.id;
                        } else {
                            query += "ids[]=" + item.id;
                        }
                    }
                    await this.$del({
                        url: "/admin/server.Task/del" + query,
                        successTip: true,
                        loading: true
                    });
                    this.getList()
                })
                .catch(() => {
                    this.$refs.table.clearSelection();
                });
        },
        async exportExcel(){
            this.$loading()
            let res = await get({
                export:true,
                url:'/admin/server.userTask/export',
                params:{
                    ...this.searchParam,
                    ...{search_time:this.searchParamCp.search_time && this.searchParamCp.search_time.length?this.searchParamCp.search_time.join(' - '):''}
                }
            })
            let a = document.createElement('a');
            var url = URL.createObjectURL(res);
            a.href = url;
            a.click();
            this.$loading().close()
        }   
        
    }
}
</script>

<style >
.el-date-editor .el-range-separator {
    padding: 0;
}</style>